import time

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.remote.webelement import WebElement

chrome = webdriver.Chrome()

chrome.get('https://fresh.jd.com/')

names = chrome.find_elements_by_class_name('item_title')


def get_prices(item: WebElement):
    price_element = item.find_elements_by_class_name('p-price')[0]
    price = price_element.find_element_by_tag_name('i').text
    name_element = item.find_elements_by_class_name('p-name')[0]
    name = name_element.find_element_by_tag_name('em').text
    print(f'price = {price}, name = {name}')
    pass


def find_type(index: int):
    element = names[index]
    element.click()
    chrome.switch_to.window(chrome.window_handles[1])
    items = chrome.find_elements_by_class_name('gl-item')
    for item in items:
        get_prices(item)
    # 切换到下一页
    body = chrome.find_element_by_tag_name('body')
    body.send_keys(Keys.ARROW_RIGHT)

    time.sleep(2)

    items = chrome.find_elements_by_class_name('gl-item')
    for item in items:
        get_prices(item)


find_type(0)
# for name in names:
#     name.click()


# chrome.quit()
